package com.example.phone.cart;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.phone.R;
import com.example.phone.base.RequestInterface;
import com.example.phone.base.ServerResponse;
import com.example.phone.bean.Cart;
import com.example.phone.bean.ShoppingCart;
import com.example.phone.bean.ShoppingCartList;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class CartListAdapter extends RecyclerView.Adapter<CartListAdapter.ViewHolder> {

    private List<Cart> mShoppingCartList;
    private Context mcontext;
    private OnCartVisibilityChangeListener onCartVisibilityChangeListener;
    private OnCartTotalPriceChangeListener onCartTotalPriceChangeListener;

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.cart_image)
        ImageView cartImage;
        @BindView(R.id.cart_name)
        TextView cartName;
        @BindView(R.id.cart_sub)
        TextView cartSub;
        @BindView(R.id.cart_minus)
        ImageView cartMinus;
        @BindView(R.id.cart_count)
        TextView cartCount;
        @BindView(R.id.cart_plus)
        ImageView cartPlus;
        @BindView(R.id.cart_productPrice)
        TextView cartProductPrice;
        @BindView(R.id.cart_delete)
        ImageView cartDelete;
        @BindView(R.id.cart_product_total)
        TextView cartProductTotal;


        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    public CartListAdapter(Context context, List<Cart> list) {
        mcontext = context;
        mShoppingCartList = list;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cart_row, viewGroup, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, int i) {
        final Cart cart = mShoppingCartList.get(i);
        viewHolder.cartName.setText(cart.getProductName());
        viewHolder.cartSub.setText(cart.getProductSubtitle());
        viewHolder.cartProductPrice.setText(mcontext.getString(R.string.rmb_price, cart.getProductPrice()));
        viewHolder.cartCount.setText(String.valueOf(cart.getQuantity()));
        viewHolder.cartProductTotal.setText(mcontext.getString(R.string.rmb_price_item_total, cart.getProductTotalPrice()));
        Glide.with(mcontext)
                .load(RequestInterface.baseImgPath + cart.getProductMainImage())
                .into(viewHolder.cartImage);


        viewHolder.cartPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cart.getQuantity() == cart.getProductStock()) {
                    toastShort("选择的数量超过库存了!");
                } else {
                    update(cart.getUserId(), cart.getProductId(), cart.getQuantity() + 1);
                }
            }
        });

        viewHolder.cartMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cart.getQuantity() == 0) {
                    viewHolder.cartMinus.setClickable(false);
                } else {
                    update(cart.getUserId(), cart.getProductId(), cart.getQuantity() - 1);
                }
            }
        });

        viewHolder.cartDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete(cart.getUserId(), cart.getProductId());
            }
        });
    }

    @Override
    public int getItemCount() {
        return mShoppingCartList.size();
    }

    private void update(int userId, int productId, int count) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.CartRequest cartRequest = retrofit.create(RequestInterface.CartRequest.class);
        Call<ServerResponse<ShoppingCartList>> call = cartRequest.updateShoppingCartList(userId, productId, count);
        call.enqueue(new Callback<ServerResponse<ShoppingCartList>>() {
            @Override
            public void onResponse(Call<ServerResponse<ShoppingCartList>> call, Response<ServerResponse<ShoppingCartList>> response) {
                if (response.body().getStatus() == 0) {
                    ShoppingCartList shoppingCartList = response.body().getData();
                    if (shoppingCartList != null) {
                        List<Cart> list = shoppingCartList.getCartProductVoList();
                        if (list != null && list.size() > 0) {
                            mShoppingCartList.clear();
                            mShoppingCartList.addAll(list);
                            notifyDataSetChanged();

                            int count = 0;
                            for (Cart s : mShoppingCartList) {
                                count += s.getQuantity();
                            }
                            onCartTotalPriceChangeListener.onTotalPriceChange(shoppingCartList.getCartTotalPrice(), count);
                            toastShort("操作成功");
                        } else {
                            toastShort("Error: List is empty!");
                        }
                    } else {
                        toastShort("Error: List is empty!");
                    }
                } else {
                    toastShort("购物车加载失败，请检查网络");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<ShoppingCartList>> call, Throwable t) {
                toastShort("购物车加载失败，请检查网络");
            }
        });
    }

    private void delete(int userId, int productId) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.CartRequest cartRequest = retrofit.create(RequestInterface.CartRequest.class);
        Call<ServerResponse<ShoppingCartList>> call = cartRequest.deleteShoppingCartList(userId, productId);
        call.enqueue(new Callback<ServerResponse<ShoppingCartList>>() {
            @Override
            public void onResponse(Call<ServerResponse<ShoppingCartList>> call, Response<ServerResponse<ShoppingCartList>> response) {
                if (response.body().getStatus() == 0) {
                    ShoppingCartList shoppingCartList = response.body().getData();
                    if (shoppingCartList != null) {
                        List<Cart> list = shoppingCartList.getCartProductVoList();
                        if (list != null && list.size() > 0) {
                            mShoppingCartList.clear();
                            mShoppingCartList.addAll(list);
                            notifyDataSetChanged();

                            int count = 0;
                            for (Cart s : mShoppingCartList) {
                                count += s.getQuantity();
                            }

                            onCartTotalPriceChangeListener.onTotalPriceChange(shoppingCartList.getCartTotalPrice(), count);
                            toastShort("操作成功");
                        } else {
                            toastShort("操作成功");
                            if (onCartVisibilityChangeListener != null) {
                                onCartVisibilityChangeListener.onVisibilityChange(false);
                            }
                        }
                    } else {
                        toastShort("Error: List is empty!");
                        onCartVisibilityChangeListener.onVisibilityChange(false);
                    }
                } else {
                    toastShort("购物车加载失败，请检查网络");
                    onCartVisibilityChangeListener.onVisibilityChange(false);
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<ShoppingCartList>> call, Throwable t) {
                toastShort("购物车加载失败，请检查网络");
            }
        });
    }

    public interface OnCartTotalPriceChangeListener {
        void onTotalPriceChange(double totalPrice, int count);
    }

    public void setOnCartTotalPriceChangeListener(OnCartTotalPriceChangeListener onCartTotalPriceChangeListener) {
        this.onCartTotalPriceChangeListener = onCartTotalPriceChangeListener;
    }


    //购物车中没有 商品时候，通知UI显示没有商品的视图
    public interface OnCartVisibilityChangeListener {
        void onVisibilityChange(boolean visible);
    }

    public void setOnCartVisibilityChangeListener(OnCartVisibilityChangeListener onCartVisibilityChangeListener) {
        this.onCartVisibilityChangeListener = onCartVisibilityChangeListener;
    }


    public void toastShort(String msg) {
        Toast.makeText(mcontext, msg, Toast.LENGTH_SHORT).show();
    }

}
